/**
 * Live GPS Tracking Application
 * Cache which uses 1 file per tile
 *
 * Copyright 2009, Ivar Clemens
 */

package nl.ivarclemens.gpstrack.tile;

import java.io.*;
import javax.microedition.io.*;
import javax.microedition.io.file.*;

public class MutliFileCache {
    
    String rootDirectory = "C:/Gallery";

    /**
     * Loads a tile from the tile-cache
     */
    public byte[] loadTile(int x, int y, int zoom) throws IOException
    {
        String filename = "file:///" + rootDirectory + "/OSM/" + zoom + "/" + x + "/" + y + ".png";

        FileConnection filecon = (FileConnection) Connector.open(filename);

        if(!filecon.exists() || !filecon.canRead())
            throw new IOException();

        InputStream is = (InputStream) filecon.openInputStream();
        byte data[];

        try {
            ByteArrayOutputStream bs = new ByteArrayOutputStream();

            int ch;

            while((ch = is.read()) != -1)
                bs.write(ch);

            data = bs.toByteArray();
        } finally {
            if(is != null)
                is.close();
        }

        return data;
    }

    public void saveTile(int x, int y, int zoom, byte data[])
    {
        if(!createTileDirectory(x, y, zoom))
            return;

        String filename = "file:///" + rootDirectory + "/OSM/" + zoom + "/" + x + "/" + y + ".png";

        try {
            FileConnection filecon = (FileConnection) Connector.open(filename);

            if(!filecon.exists());
                filecon.create();

            OutputStream os = (OutputStream) filecon.openOutputStream();
            os.write(data);
        } catch(Exception e) {
        }
    }

    private boolean createDirectory(String name)
    {
        try {
            FileConnection filecon = (FileConnection)
                Connector.open(name);

            if(!filecon.exists())
                filecon.mkdir();

            return filecon.isDirectory();
        } catch(Exception e) {

        }

        return false;
    }

    private boolean createTileDirectory(int x, int y, int zoom)
    {
        String directory = "file:///" + rootDirectory;

        if(!createDirectory(directory + "/OSM"))
            return false;

        if(!createDirectory(directory + "/OSM/" + zoom))
            return false;

        return createDirectory(directory + "/OSM/" + zoom + "/" + x);
    }
}
